#pragma once

#include <iostream>
#include <unistd.h>
#include "Socket.hpp"
#include "Log.hpp"

using namespace SocketModule;
using namespace LogModule;

class SelectServer
{
    static const int size = sizeof(fd_set) * 8;
    static const int defaultfd = -1;

public:
    SelectServer(int port)
        : _listensock(std::make_unique<TcpSocket>()),
          _isrunning(false)
    {
        _listensock->BuildListenSocketMethod(port);
        for (int i = 0; i < size; i++)
        {
            _fd_array[i] = defaultfd;
        }
        _fd_array[0] = _listensock->Fd();
    }

    void Start()
    {
        _isrunning = true;
        while (_isrunning)
        {
            fd_set rfds;
            int maxfd = defaultfd;
            FD_ZERO(&rfds);
            // FD_SET(_listensock->Fd(), &rfds);
            for (int i = 0; i < size; i++)
            {
                if (_fd_array[i] == defaultfd)
                    continue;
                FD_SET(_fd_array[i], &rfds);
                maxfd = std::max(_fd_array[i], maxfd);
            }
            PrintFd();
            struct timeval timeout = {2, 0};
            int n = select(maxfd + 1, &rfds, nullptr, nullptr, &timeout);
            switch (n)
            {
            case -1:
                LOG(LogLevel::ERROR) << "select error";
                break;
            case 0:
                LOG(LogLevel::INFO) << "time out...";
                break;
            default:
                LOG(LogLevel::DEBUG) << "有事件就绪...";
                Dispatcher(rfds);
                break;
            }
        }
        Stop();
    }

    void Dispatcher(fd_set &rfds)
    {
        for (int i = 0; i, size; i++)
        {
            if (_fd_array[i] == defaultfd)
                continue;
            if (FD_ISSET(_fd_array[i], &rfds))
            {
                if (_fd_array[i] == _listensock->Fd())
                {
                    Accepter();
                }
                else
                {
                    Recver(_fd_array[i], i);
                }
            }
        }
    }

    void Accepter()
    {
        InetAddr client;
        int fd = _listensock->Accept(&client);
        if (fd >= 0)
        {
            LOG(LogLevel::INFO) << "get a new link, sockfd: " << fd;
            int pos = 0;
            for (; pos < size; pos++)
            {
                if (_fd_array[pos] == defaultfd)
                    break;
            }

            if (pos == size)
            {
                LOG(LogLevel::WARNING) << "select server full";
                close(fd);
            }
            else
            {
                _fd_array[pos] = fd;
            }
        }
    }

    void Recver(int fd, int pos)
    {
        char buffer[1024];
        ssize_t n = recv(fd, buffer, sizeof(buffer) - 1, 0);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "client say@ " << buffer << std::endl;
        }
        else if (n == 0)
        {
            LOG(LogLevel::INFO) << "client quit...";
            _fd_array[pos] = defaultfd;
            close(fd);
        }
        else
        {
            LOG(LogLevel::ERROR) << "recv error";
            _fd_array[pos] = defaultfd;
            close(fd);
        }
    }

    void PrintFd()
    {
        std::cout << "fd_array[]: ";
        for (int i = 0; i < size; i++)
        {
            if (_fd_array[i] == defaultfd)
                continue;
            std::cout << _fd_array[i] << " ";
        }
        std::cout << std::endl;
    }

    void Stop()
    {
        _isrunning = false;
    }

    ~SelectServer()
    {
    }

private:
    std::unique_ptr<Socket> _listensock;
    bool _isrunning;
    int _fd_array[size];
};